#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "gnuplot_i.h"

#define N 1024

typedef double trame[N];

gnuplot_ctrl * plot_init(char * style){
  gnuplot_ctrl * h = gnuplot_init();
  gnuplot_setstyle(h, style);
  return h;
}

void plot_temporal(gnuplot_ctrl *h, trame x_axis,trame y_axis, int n, char * nom){
  gnuplot_resetplot(h);
  gnuplot_plot_xy(h, x_axis, y_axis, n, nom);
  sleep(1);
}

/***********************************************/
/***********************************************/
/***********************************************/

FILE * sound_file_open_read(char *nom){
  int taille = 31 + strlen(nom);
  char *s = malloc(taille * sizeof(*s));
  strcat(s, "sox ");
  strcat(s, nom);
  strcat(s, " -r44100 -s2 -c1 tmp-in.raw"); 
  system(s);
  FILE * f = fopen("tmp-in.raw", "rb");
  return f;
}


int sound_file_read(FILE * f, trame t){
  short tmp[N];
  int nmemb = fread(tmp, sizeof(short), N, f);
  for(int i=0; i<N; i++){
    t[i] = (double)tmp[i];
    t[i] /= 32768;
  }
  return nmemb;
}

void sound_file_close_read(FILE * f){
  fclose(f);
}

/***********************************************/

FILE * sound_file_open_write(char * nom){
  FILE * f = fopen(nom, "wb");
  return f;
}

int sound_file_write(FILE * f, trame t){
  short tmp[N];
  for(int i=0; i<N; i++)
    tmp[i] = (short)(32768 * t[i]);
  int nmemb = fwrite(tmp, sizeof(short), N, f);
  return nmemb;
}

void sound_file_close_write(FILE * f){
  fclose(f);
  system("sox -r44100 -s2 -c1 tmp-out.raw out.wav");

}

/***********************************************/

void minute_silence(){
  FILE * out = sound_file_open_write("tmp-out.raw");
  int echantillon_minute = 44100 * 60;
  trame tmp;

  int q =  echantillon_minute / N;

  for(int i=0; i<N; i++)
    tmp[i] = 0.0;

  for(int i=0; i<q; i++)
    sound_file_write(out, tmp);

  sound_file_close_write(out);
}

/**********************/
#define PI 3.14159265

double a(double t){
  return 0.5 * sin(2 * PI * 440 * t/44100);
}
void sinusoide(){

  FILE * out = sound_file_open_write("tmp-out.raw");

  double tab[44100]; //1sec
  for(int i=0; i<44100; i++)
    tab[i] = a(i);
  
  short tmp[44100];
  
  for(int i=0; i<44100; i++)
    tmp[i] = (short)(32768 * tab[i]);

  fwrite(tmp, sizeof(short), 44100, out);
  sound_file_close_write(out);
}

/***********************************************/
int main(int argc, char **argv){
  sinusoide();
  
  return 0;
}
		    
